from module.huada.entity.base_entity import BaseEntity
from plugin import MSsqlClient, Mylogger,MyTime
from module.huada.entity.department_entity import department_cache, stationid, init_department_cache


class PersonEntity(BaseEntity):
    """
    {"emailAddress":"aalbert@completegenomics.com","userId":"aalbert","company":"70100","companyName":"COMPLETE GENOMICS,INC.","businessUnit":"B4","businessUnitName":"华大智造","division":"B4BN","divisionName":"MGI US CG","department":"BCInfo","departmentName":"BioChem.Info","customString2":"6151","customString2Name":"BioChemBioInfo","customString3":"","customString3Name":"","customString4":"","customString4Name":"","emplStatus":"627","managerId":"","gender":"F","customString1":"614","lastModifiedDateTime":"2022-07-28 16:45:02.0","location":"","locationZhCn":null,"areaCode":null,"phoneNumber":null,"preferredName":"AlbertAlayna","firstDateWorked":"2015-07-13","endDate1":"2018-02-02","originalStartDate":"2014-07-08"}
    """
    url = "tunion/ehrmainempinfo"
    table_name = "person"
    create_table = True
    api_data_list = []
    get_time = "2000-01-01 00:00:00"
    order_by = "lastModifiedDateTime"
    sync_list = []
    write_back_dict = {}
    update_cache_time = "2000-01-01 00:00:00"

    # 初始化
    def __init__(self, **kwargs):
        self.emailAddress = kwargs.get('emailAddress')  # 邮箱
        self.userId = kwargs.get('userId')  # 用户id
        self.company = kwargs.get('company')  # 法人编码
        self.companyName = kwargs.get('companyName')  # 法人名称
        self.businessUnit = kwargs.get('businessUnit')  # O2编码
        self.businessUnitName = kwargs.get('businessUnitName')  # O2名称
        self.division = kwargs.get('division')  # O3编码
        self.divisionName = kwargs.get('divisionName')  # O3名称
        self.department = kwargs.get('department')  # O4编码
        self.departmentName = kwargs.get('departmentName')  # O4名称
        self.customString2 = kwargs.get('customString2')  # O5编码
        self.customString2Name = kwargs.get('customString2Name')  # O5名称
        self.customString3 = kwargs.get('customString3')  # O6编码
        self.customString3Name = kwargs.get('customString3Name')  # O6名称
        self.customString4 = kwargs.get('customString4')  # O7编码
        self.customString4Name = kwargs.get('customString4Name')  # O7名称
        self.emplStatus = kwargs.get('emplStatus')  # 员工状态，623在职，其他离职
        self.managerId = kwargs.get('managerId')  # 上级领导工号id
        self.gender = kwargs.get('gender')  # 性别 M男 F女
        self.customString1 = kwargs.get('customString1')  # 工号  主键
        self.lastModifiedDateTime = kwargs.get('lastModifiedDateTime')  # 最后修改时间
        self.location = kwargs.get('location')  # 城市编码
        self.locationZhCn = kwargs.get('locationZhCn')  # 城市名称
        self.areaCode = kwargs.get('areaCode')  # 区号
        self.phoneNumber = kwargs.get('phoneNumber')  # 电话号码
        self.preferredName = kwargs.get('preferredName')  # 姓名
        self.preferredName = self.preferredName.replace("'", ' ') if self.preferredName else self.preferredName
        self.firstDateWorked = kwargs.get('firstDateWorked') or ''  # 参加工作日期
        self.firstDateWorked = self.firstDateWorked.replace("None", "")
        self.endDate1 = kwargs.get('endDate1') or ''  # 离职日期
        self.endDate1 = self.endDate1.replace("None", "")
        self.originalStartDate = kwargs.get('originalStartDate') or ''  # 入职日期
        self.originalStartDate = self.originalStartDate.replace("None", "")
        self.isdeal = kwargs.get('isdeal') or 0  # 是否处理过，0未处理，1已处理, -n 代表第n次处理失败
        self.id = kwargs.get('id') or 0

    @classmethod
    def do_sync(cls, client: MSsqlClient, objs: list[BaseEntity]):
        """
        同步数据
        :return:
        """
        # if is_first_sync:
        #     # 初始化部门缓存
        #     init_department_cache()  # 部门加载完成后，缓存并不完整，最后的一级部门没有加入缓存，这里重新加载一次
        #     is_first_sync = False

        # 每天更新一次部门缓存
        if MyTime.timestamp() - int(MyTime.timestampfrom(cls.update_cache_time)) > 24 * 60 * 60:
            # 初始化部门缓存
            init_department_cache()
            cls.update_cache_time = MyTime.timestr()

        result_num = [0, 0]  # 写，删
        for obj in objs:
            usercode = obj.customString1
            # 人员表里面排除外部人员信息，直接回写1
            if 'link' in usercode:
                cls.write_back_dict[str(1)].append(str(obj.id))
                continue
            user_jobnum = obj.userId
            department_id = ''
            department_group = ['customString4', 'customString3', 'customString2', 'department', 'division', 'businessUnit']
            for item in department_group:
                if getattr(obj, item) != '':
                    department = getattr(obj, item)
                    # 获取当前遍历的index
                    index = 6 - department_group.index(item)  # 计算level
                    if department_cache.get(index) and department_cache[index].get(department):
                        department_id = department_cache[index][department]
                    if department_id == '':
                        Mylogger.info(f"person {usercode} department {department} level {index} is not found")
                    break
            result = 0  # 处理结果
            if department_id != '':
                # Mylogger.error(f"person {usercode} department is not found")
                # continue
            # else:
                if obj.emplStatus == '623':  # 在职
                    gender = 1 if obj.gender == 'M' else 0
                    result = client.execute(f"""
                    if not exists (select 1 from acscon_user where usercode='{usercode}')
                    begin
                        declare @id varchar(36) = newid()
                        insert into acscon_user (id,stationid,usercode,name,type,sex,pwd,email,phone,city,validdatebegin,validdateend,status,descr,company,department,jobnum)
                        values (@id,'{stationid}','{usercode}','{obj.preferredName}',1,{gender},'fhWuQ7Ia6cM=','{obj.emailAddress}','{obj.phoneNumber}','{obj.locationZhCn}','{obj.originalStartDate}','{obj.endDate1}',1,'','{obj.company}','','{user_jobnum}')

                        insert into acscon_groupmember (stationid,gid,uid) values ('{stationid}','{department_id}',@id)
                    end
                    else
                    begin
                        declare @id1 varchar(36) = (select id from acscon_user where usercode = '{usercode}')
                        update acscon_user set name = '{obj.preferredName}',sex = {gender},email = '{obj.emailAddress}',phone = '{obj.phoneNumber}',city = '{obj.locationZhCn}',validdatebegin = '{obj.originalStartDate}',validdateend = '{obj.endDate1}',descr = '',company = '{obj.company}',jobnum = '{user_jobnum}' where usercode = '{usercode}'
                        if not exists (select 1 from acscon_groupmember where gid = '{department_id}' and uid = @id1)
                            update acscon_groupmember set gid = '{department_id}' where uid = @ID1
                    end
                    """)
                    # result = 1
                    result_num[0] += 1
                else:  # 离职
                    result = client.execute(f"""
                    if exists (select 1 from acscon_user where usercode = '{usercode}')
                    begin
                        delete from acscon_groupmember where uid = (select id from acscon_user where usercode = '{usercode}')
                        delete from acscon_user where usercode = '{usercode}'
                    end
                    """)
                    if result == -1:
                        # Mylogger.info(f"person {usercode} delete failed, not found")
                        result = 1  # 未找到不算错误, 也不需要再次处理
                    # elif result == 2:
                    result_num[1] += 1

            if result is not None:
                key = 1 if result > 0 else (int(obj.isdeal) - 1)
                if not cls.write_back_dict.__contains__(str(key)):
                    cls.write_back_dict[str(key)] = []

                cls.write_back_dict[str(key)].append(str(obj.id))

        Mylogger.info(f"person同步成功, write {result_num[0]}, delete {result_num[1]}")
        return super().do_sync(client, objs)